package com.dd.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.reggie.common.CustomException;
import com.dd.reggie.dto.SetmealDto;
import com.dd.reggie.entity.Setmeal;
import com.dd.reggie.entity.SetmealDish;
import com.dd.reggie.mapper.SetmealMapper;
import com.dd.reggie.service.SetmealDishService;
import com.dd.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService{

    @Autowired
    private SetmealDishService setmealDishService;

    //加入事务注解，两次保存操作要么全成功要么全失败
    @Transactional
    public void saveWithSetmeal(SetmealDto setmealDto) {
        //首先保存到Setmeal中生成ID
        this.save(setmealDto);

        //提取到setmealId加入到setmealDishs中去
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        setmealDishes.stream().map(item -> {

            item.setSetmealId(setmealDto.getId());
            return item;

        }).collect(Collectors.toList());

        setmealDishService.saveBatch(setmealDishes);

    }

    @Transactional
    public void updateWithSetmeal(SetmealDto setmealDto) {
        //首先修改setmeal表
        this.updateById(setmealDto);

        //然后改首先修改setmeal_dish表
        //先删除套餐包含的菜品
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, setmealDto.getId());
        setmealDishService.remove(queryWrapper);

        //再新增加入的菜品
        List<SetmealDish> list = setmealDto.getSetmealDishes();

        list = list.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        setmealDishService.saveBatch(list);

    }

    @Transactional
    public void removeWithSetmeal(List<Long> ids) {

        //判断所选套餐是否均为停售状态
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getStatus, 1);
        int count = this.count(queryWrapper);
        if(count > 0){
            throw new CustomException("所选套餐不全为停售状态");
        }

        //删除套餐
        this.removeByIds(ids);

        //删除套餐菜品
        //delete from setmeal_dish where setmeal_id in ids
        LambdaQueryWrapper<SetmealDish> queryWrapperDish = new LambdaQueryWrapper<>();
        queryWrapperDish.in(SetmealDish::getSetmealId, ids);
        setmealDishService.list(queryWrapperDish);
        setmealDishService.remove(queryWrapperDish);

    }
}
